package com.example.qihuibao.widget.dialog

import android.app.AlertDialog
import android.app.TimePickerDialog
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.base.BaseDialogFragment
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Global
import com.example.qihuibao.enum.MealStatus
import com.example.qihuibao.enum.OrderMode
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.EnumUtils
import com.example.qihuibao.utils.extension.toast
import com.example.qihuibao.widget.view.CommonRecyclerView
import com.example.qihuibao.widget.view.EdittextWithText
import com.example.qihuibao.widget.view.TextViewWithText

/**
 *@author: cww
 *@desc:企业信息操作
 *@date: 5/16/23 10:58 AM
 */
class MealInfoQueryDialog(val mealId:String) : BaseDialogFragment(R.layout.dialog_meal_info_query) {
    val empTypeList = mutableListOf<EmpType>()
    var modifing = false
    var selectStat:MealStatus? = null
    var selectOrderMode:OrderMode? = null
    //
    val mealSetList = mutableListOf<MealSet>()

    override fun initView() {
        mView?.findViewById<View>(R.id.iv_close)?.setOnClickListener { dismiss() }
        (activity as MainActivity).getMainViewModel().queryMealInfo(ReqQueryMealInfoBean(Global.canteenId, mealId)).observe(this) { it ->
            if (it.RetCode == "0") {
                mView?.findViewById<TextView>(R.id.tv_CantID)?.text = "餐厅ID：${Global.canteenId}"
                mView?.findViewById<TextView>(R.id.tv_MealID)?.text = "餐别ID：${it.MealID}"
                mView?.findViewById<EdittextWithText>(R.id.et_MealName)?.setContent("${it.MealName}")
                val stat = EnumUtils.getMealStatus(it.Status?:"0")
                selectStat = stat[0]
                val spStatus = mView?.findViewById<Spinner>(R.id.sp_Status)
                spStatus?.isEnabled = false
                spStatus?.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, stat)
                spStatus?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectStat = stat[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                mView?.findViewById<CheckBox>(R.id.cb_OrderFlag)?.isChecked = it.OrderFlag == "1"
                mView?.findViewById<CheckBox>(R.id.cb_SpotFlag)?.isChecked = it.SpotFlag == "1"
                mView?.findViewById<CheckBox>(R.id.cb_CancelFlag)?.isChecked = it.CancelFlag == "1"
                mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_1)?.isChecked = EnumUtils.getEnable(it.WeekCalendar?:"", 1)
                mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_2)?.isChecked = EnumUtils.getEnable(it.WeekCalendar?:"", 2)
                mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_3)?.isChecked = EnumUtils.getEnable(it.WeekCalendar?:"", 3)
                mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_4)?.isChecked = EnumUtils.getEnable(it.WeekCalendar?:"", 4)
                mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_5)?.isChecked = EnumUtils.getEnable(it.WeekCalendar?:"", 5)
                mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_6)?.isChecked = EnumUtils.getEnable(it.WeekCalendar?:"", 6)
                mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_7)?.isChecked = EnumUtils.getEnable(it.WeekCalendar?:"", 7)
                mView?.findViewById<TextViewWithText>(R.id.tv_UseBeginTime)?.setText(content = "${if (it.UseBeginTime.isNullOrEmpty()) "点击选择" else it.UseBeginTime}") {
                    showTimePicker {
                        mView?.findViewById<TextViewWithText>(R.id.tv_UseBeginTime)?.setContent(it)
                    }
                }
                mView?.findViewById<TextViewWithText>(R.id.tv_UseEndTime)?.setText(content = "${if (it.UseEndTime.isNullOrEmpty()) "点击选择" else it.UseEndTime}") {
                    showTimePicker {
                        mView?.findViewById<TextViewWithText>(R.id.tv_UseEndTime)?.setContent(it)
                    }
                }
                mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseBeginTime)?.setText(content = "${if (it.SpotUseBeginTime.isNullOrEmpty()) "点击选择" else it.SpotUseBeginTime}") {
                    showTimePicker {
                        mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseBeginTime)?.setContent(it)
                    }
                }
                mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseEndTime)?.setText(content = "${if (it.SpotUseEndTime.isNullOrEmpty()) "点击选择" else it.SpotUseEndTime}") {
                    showTimePicker {
                        mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseEndTime)?.setContent(it)
                    }
                }
                mView?.findViewById<TextViewWithText>(R.id.tv_OrderDeadlineTime)?.setText(content = "${if (it.OrderDeadlineTime.isNullOrEmpty()) "点击选择" else it.OrderDeadlineTime}") {
                    showTimePicker {
                        mView?.findViewById<TextViewWithText>(R.id.tv_OrderDeadlineTime)?.setContent(it)
                    }
                }
                mView?.findViewById<TextViewWithText>(R.id.tv_CancelDeadlineTime)?.setText(content = "${if (it.CancelDeadlineTime.isNullOrEmpty()) "点击选择" else it.CancelDeadlineTime}") {
                    showTimePicker {
                        mView?.findViewById<TextViewWithText>(R.id.tv_CancelDeadlineTime)?.setContent(it)
                    }
                }
                mView?.findViewById<EdittextWithText>(R.id.et_OrderDeadlineDate)?.setContent("${it.OrderDeadlineDate}")
                mView?.findViewById<EdittextWithText>(R.id.et_CancelDeadlineDate)?.setContent("${it.CancelDeadlineDate}")
                mView?.findViewById<EdittextWithText>(R.id.et_PerOrderLimit)?.setContent("${it.PerOrderLimit}")
                mView?.findViewById<EdittextWithText>(R.id.et_PerSpotLimit)?.setContent("${it.PerSpotLimit}")
                mView?.findViewById<EdittextWithText>(R.id.et_PerTotalLimit)?.setContent("${it.PerTotalLimit}")
                mView?.findViewById<EdittextWithText>(R.id.et_AllOrderLimit)?.setContent("${it.AllOrderLimit}")
                mView?.findViewById<EdittextWithText>(R.id.et_AllSpotLimit)?.setContent("${it.AllSpotLimit}")
                mView?.findViewById<EdittextWithText>(R.id.et_AllTotalLimit)?.setContent("${it.AllTotalLimit}")
                val orderMode = EnumUtils.getOrderMode(it.OrderMode)
                selectOrderMode = orderMode[0]
                val spOrderMode = mView?.findViewById<Spinner>(R.id.sp_OrderMode)
                spOrderMode?.isEnabled = false
                spOrderMode?.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, orderMode)
                spOrderMode?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectOrderMode = orderMode[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                mView?.findViewById<CheckBox>(R.id.cb_DeliverFlag)?.isChecked = it.DeliverFlag == "1"
                if (!it.MealSetlList.isNullOrEmpty()) {
                    mealSetList.clear()
                    mealSetList.addAll(it.MealSetlList)
                }
                mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList)?.init(
                    R.layout.item_text_with_delete,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    mealSetList,
                    {parent, pos ->
                        if (mealSetList.isNotEmpty()) {
                            parent.findViewById<TextView>(R.id.tv_content).text = "套餐ID: ${mealSetList[pos].MealSetID}\n" +
                                    "套餐名称: ${mealSetList[pos].MealSetName}\n" +
                                    "状态: ${if (mealSetList[pos].Status == "0") "不开餐" else "开餐"}\n" +
                                    "个人订餐限额: ${mealSetList[pos].PerOrderLimit}\n" +
                                    "个人现场限额: ${mealSetList[pos].PerSpotLimit}\n" +
                                    "个人总量限额: ${mealSetList[pos].PerTotalLimit}\n" +
                                    "总订餐限额: ${mealSetList[pos].AllOrderLimit}\n" +
                                    "总现场限额: ${mealSetList[pos].AllSpotLimit}\n" +
                                    "总的总量限额: ${mealSetList[pos].AllTotalLimit}\n"
                        }
                    },
                    {
                        if (modifing) {
                            showMealSetDialog(it, mealSetList[it])
                        }
                    },
                    {pos, itemView ->
                        itemView.findViewById<TextView>(R.id.tv_delete).visibility = if (itemView.findViewById<TextView>(R.id.tv_delete).visibility == View.VISIBLE) View.GONE else View.VISIBLE
                        itemView.findViewById<TextView>(R.id.tv_delete).setOnClickListener {
                            mealSetList.removeAt(pos)
                            mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList)?.adapter?.notifyDataSetChanged()
                        }
                    }
                )
                if (!it.FeeList.isNullOrEmpty()) {
                    mView?.findViewById<CommonRecyclerView>(R.id.rv_FeeList)?.init(
                        R.layout.item_text,
                        LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                        it.FeeList,
                        {parent, pos ->
                            (parent as TextView).text = "收费标准ID: ${it.FeeList[pos].FeeID}\n" +
                                    "收费标准名称: ${it.FeeList[pos].FeeName}\n"
                        }
                    )
                }
                mView?.findViewById<View>(R.id.iv_add_mealset)?.setOnClickListener {
                    showMealSetDialog()
                }
                //
                mView?.findViewById<View>(R.id.tv_modify)?.setOnClickListener {
                    modifing = !modifing
                    mView?.findViewById<TextView>(R.id.tv_modify)?.text = if (modifing) "取消" else "修改"
                    spStatus?.isEnabled = modifing
                    spOrderMode?.isEnabled = modifing
                    mView?.findViewById<EdittextWithText>(R.id.et_MealName)?.enableContent(modifing)
                    mView?.findViewById<CheckBox>(R.id.cb_OrderFlag)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_SpotFlag)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_CancelFlag)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_1)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_2)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_3)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_4)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_5)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_6)?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_7)?.isEnabled = modifing
                    mView?.findViewById<TextViewWithText>(R.id.tv_UseBeginTime)?.enableContent(modifing)
                    mView?.findViewById<TextViewWithText>(R.id.tv_UseEndTime)?.enableContent(modifing)
                    mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseBeginTime)?.enableContent(modifing)
                    mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseEndTime)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_OrderDeadlineDate)?.enableContent(modifing)
                    mView?.findViewById<TextViewWithText>(R.id.tv_OrderDeadlineTime)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_CancelDeadlineDate)?.enableContent(modifing)
                    mView?.findViewById<TextViewWithText>(R.id.tv_CancelDeadlineTime)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_PerOrderLimit)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_PerSpotLimit)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_PerTotalLimit)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_AllOrderLimit)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_AllSpotLimit)?.enableContent(modifing)
                    mView?.findViewById<EdittextWithText>(R.id.et_AllTotalLimit)?.enableContent(modifing)
                    mView?.findViewById<CheckBox>(R.id.cb_DeliverFlag)?.isEnabled = modifing
                    mView?.findViewById<View>(R.id.iv_add_mealset)?.visibility = if (modifing) View.VISIBLE else View.GONE
                    mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList)?.adapter?.notifyDataSetChanged()
                    if (!modifing) {
                        initView()
                    }
                }
                mView?.findViewById<View>(R.id.tv_update)?.setOnClickListener {
                    modifing = true
                    mView?.findViewById<View>(R.id.tv_modify)?.performClick()
                    updateMealInfo()
                }
            }else {
                activity?.toast("查询失败")
            }
        }
    }

    private fun showMealSetDialog(index:Int=0, bean:MealSet? = null) {
        val view = LayoutInflater.from(activity).inflate(R.layout.dialog_add_mealset, null)
        val dialogBuilder = AlertDialog.Builder(activity)
        dialogBuilder.setView(view)
        val dialog = dialogBuilder.show()
        //
        var status = "0"
        var stat = EnumUtils.getMealStatus("0")
        if (bean != null) {
            view.findViewById<EdittextWithText>(R.id.et_MealSetID).setContent(bean.MealSetID!!)
            view.findViewById<EdittextWithText>(R.id.et_MealSetName).setContent(bean.MealSetName!!)
            stat = EnumUtils.getMealStatus(bean.Status!!)
            view.findViewById<EdittextWithText>(R.id.et_PerOrderLimit).setContent("${bean.PerOrderLimit}")
            view.findViewById<EdittextWithText>(R.id.et_PerSpotLimit).setContent("${bean.PerSpotLimit}")
            view.findViewById<EdittextWithText>(R.id.et_PerTotalLimit).setContent("${bean.PerTotalLimit}")
            view.findViewById<EdittextWithText>(R.id.et_AllOrderLimit).setContent("${bean.AllOrderLimit}")
            view.findViewById<EdittextWithText>(R.id.et_AllSpotLimit).setContent("${bean.AllSpotLimit}")
            view.findViewById<EdittextWithText>(R.id.et_AllTotalLimit).setContent("${bean.AllTotalLimit}")
        }
        val spStatus = view.findViewById<Spinner>(R.id.sp_Status)
        spStatus?.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, stat)
        spStatus?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                status = stat[position].value
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        view.findViewById<View>(R.id.btn_cancel).setOnClickListener { dialog.dismiss() }
        view.findViewById<View>(R.id.btn_ok).setOnClickListener {
            if (view.findViewById<EdittextWithText>(R.id.et_MealSetID).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_MealSetName).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_PerOrderLimit).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_PerSpotLimit).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_PerTotalLimit).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_AllOrderLimit).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_AllSpotLimit).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_AllTotalLimit).getContent().isEmpty()
            ) {
                activity?.toast("输入不能为空")
                return@setOnClickListener
            }
            if (bean != null) {
                mealSetList.remove(bean)
            }
            for (item in mealSetList) {
                if (item.MealSetID == view.findViewById<EdittextWithText>(R.id.et_MealSetID).getContent()) {
                    activity?.toast("已有相同ID")
                    return@setOnClickListener
                }
            }
            mealSetList.add(index, MealSet(
                view.findViewById<EdittextWithText>(R.id.et_MealSetID).getContent(),
                view.findViewById<EdittextWithText>(R.id.et_MealSetName).getContent(),
                status,
                view.findViewById<EdittextWithText>(R.id.et_PerOrderLimit).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_PerSpotLimit).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_PerTotalLimit).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_AllOrderLimit).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_AllSpotLimit).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_AllTotalLimit).getContent().toInt()
            ))
            mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList)?.adapter?.notifyDataSetChanged()
            dialog.dismiss()
        }
    }

    private fun showTimePicker(selected:(time:String)->Unit) {
        TimePickerDialog(activity, { view, hourOfDay, minute ->
            selected("${if (hourOfDay<10) "0$hourOfDay" else hourOfDay}:${if (minute<10) "0$minute" else minute}")
        }, 0, 0, true).show()
    }

    private fun updateMealInfo() {
        val mealSets = mutableListOf<MealSet>()
        for (item in mealSetList) {
            val bean = MealSet(item.MealSetID!!, item.MealSetName!!, item.Status!!, item.PerOrderLimit, item.PerSpotLimit, item.PerTotalLimit, item.AllOrderLimit, item.AllSpotLimit, item.AllTotalLimit)
            mealSets.add(bean)
        }
        val req = ReqUpdateMealInfoBean(
            Global.canteenId,
            mealId,
            mView?.findViewById<EdittextWithText>(R.id.et_MealName)?.getContent()?:"",
            selectStat?.value?:"0",
            if (mView?.findViewById<CheckBox>(R.id.cb_OrderFlag)?.isChecked == true) "1" else "0",
            if (mView?.findViewById<CheckBox>(R.id.cb_SpotFlag)?.isChecked == true) "1" else "0",
            if (mView?.findViewById<CheckBox>(R.id.cb_CancelFlag)?.isChecked == true) "1" else "0",
            "${if (mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_1)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_2)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_3)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_4)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_5)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_6)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_WeekCalendar_7)?.isChecked == true) "1" else "0"}",
            mView?.findViewById<TextViewWithText>(R.id.tv_UseBeginTime)?.getContent()?:"",
            mView?.findViewById<TextViewWithText>(R.id.tv_UseEndTime)?.getContent()?:"",
            mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseBeginTime)?.getContent()?:"",
            mView?.findViewById<TextViewWithText>(R.id.tv_SpotUseEndTime)?.getContent()?:"",
            mView?.findViewById<EdittextWithText>(R.id.et_OrderDeadlineDate)?.getContent()?:"",
            mView?.findViewById<TextViewWithText>(R.id.tv_OrderDeadlineTime)?.getContent()?:"",
            mView?.findViewById<EdittextWithText>(R.id.et_CancelDeadlineDate)?.getContent()?:"",
            mView?.findViewById<TextViewWithText>(R.id.tv_CancelDeadlineTime)?.getContent()?:"",
            mView?.findViewById<EdittextWithText>(R.id.et_PerOrderLimit)?.getContent()!!.toInt(),
            mView?.findViewById<EdittextWithText>(R.id.et_PerSpotLimit)?.getContent()!!.toInt(),
            mView?.findViewById<EdittextWithText>(R.id.et_PerTotalLimit)?.getContent()!!.toInt(),
            mView?.findViewById<EdittextWithText>(R.id.et_AllOrderLimit)?.getContent()!!.toInt(),
            mView?.findViewById<EdittextWithText>(R.id.et_AllSpotLimit)?.getContent()!!.toInt(),
            mView?.findViewById<EdittextWithText>(R.id.et_AllTotalLimit)?.getContent()!!.toInt(),
            mealSets
        )
        (activity as MainActivity).getMainViewModel().updateMealInfo(req).observe(this) {
            activity?.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
            initView()
        }
    }

}